<template>
  <div>
    <div>
      <InputTextArea
        v-model:value="conds"
        :rows="5"
        @change="setEmit"
        :readonly="isScriptEditable > 0"
      />
    </div>
    <div></div>
    <div class="flex flex-wrap gap-2 items-center">
      <div
        v-for="(item, index) in tjList"
        :key="index"
        @click="handleClickItem(item.value)"
        :title="item.label + item.descrip"
        class="hover:underline cursor-pointer"
      >
        {{ item.label }}</div
      >
      <a-button
        type="primary"
        @click="handleDesign"
        class="mt-2 mb-2"
        :disabled="isScriptEditable == 2"
        >设计器</a-button
      >
    </div>
    <div>
      注：<br />
      1、条件不能以and开头<br />
      2、当为集团版时，如果记录不需要限定为本单位的，则点击维护，在源模块的过滤条件中配置“单位”为不限制
    </div>
    <div>
      源表单中的
      <Select
        style="width: 130px"
        v-model:value="tjObj.sourceCondField"
        :options="formGetFieldsData"
        :field-names="{ label: 'title', value: 'name' }"
        :get-popup-container="getPopupContainer"
      />
      <Select
        style="width: 130px; margin: 0 5px"
        :options="tjOptions"
        v-model:value="tjObj.token"
        :get-popup-container="getPopupContainer"
      />
      主表单中的
      <Select
        style="width: 130px"
        v-model:value="tjObj.fieldOpener"
        :options="formGetFieldsDataMian"
        :field-names="{ label: 'title', value: 'name' }"
        :get-popup-container="getPopupContainer"
      />
      <a-button type="primary" @click="handleCreate" class="mt-2 mb-2 ml-2">添加</a-button>
    </div>
    <DesignIframe
      ref="ifrmRef"
      @register="registerDesignIframeView"
      @success="handleSuccess"
      :zIndex="10000"
    />
  </div>
</template>
<script lang="ts" setup>
  import { ref, unref, onUnmounted, watch, onMounted } from 'vue';
  import { useModal } from '/@/components/Modal';
  import { Input, Select, message } from 'ant-design-vue';
  import { useRouter } from 'vue-router';
  import { DesignIframe } from '/@/views/system/workflow/flowManagement/modules/flowPicture/modules/modules/index';
  import { useUserStore } from '/@/store/modules/user';
  import { getFormGetFields } from '/@/api/flowManage/flowManage';
  import { isArray } from '/@/utils/is';
  const InputTextArea = Input.TextArea;
  const { currentRoute } = useRouter();
  const isScriptEditable = ref(0);

  const emit = defineEmits(['update:modelValue']);
  const props = defineProps({
    modelValue: {
      type: String,
      default: '',
    },
    formGetFieldsData: {
      type: Array,
      default: () => [],
    },
  });

  const setEmit = () => {
    emit('update:modelValue', conds.value);
  };
  const conds = ref('');

  watch(
    () => props.modelValue,
    (newVal) => {
      conds.value = newVal;
    },
    {
      immediate: true,
    },
  );
  const [registerDesignIframeView, { openModal, closeModal }] = useModal();
  const handleDesign = () => {
    openModal(true, {
      scriptStr: unref(conds),
      formCode: currentRoute.value?.query?.formCode,
    });
  };
  const handleSuccess = (value) => {
    console.log('handleSuccess', value);
    conds.value = value;
    setEmit();
  };

  const tjList = [
    {
      label: '当前日期',
      value: '{$curDate}',
      descrip: '',
    },
    {
      label: '当前用户',
      value: '={$curUser}',
      descrip: '',
    },
    {
      label: '当前用户所在的部门',
      value: 'in ({$curUserDept})',
      descrip: '',
    },
    {
      label: '当前用户的角色',
      value: 'in ({$curUserRole})',
      descrip: '',
    },
    {
      label: '主模块记录的ID',
      value: '{$mainId}',
      descrip:
        ',可用于流程中拉单时获取流程表单记录的ID、模块编辑时的主模块ID或与操作列中自定义链接联用',
    },
    {
      label: '当前用户管理的部门',
      value: 'in ({$admin.dept})',
      descrip: '用户可以管理的部门',
    },
  ];

  const handleClickItem = (value) => {
    conds.value += ` ${value}`;
    setEmit();
  };

  const tjOptions = [
    {
      label: '等于',
      value: '=',
    },
    {
      label: '大于等于',
      value: '>=',
    },
    {
      label: '大于',
      value: '>',
    },
    {
      label: '小于等于',
      value: '<=',
    },
    {
      label: '小于',
      value: '<',
    },
    {
      label: '不等于',
      value: '<>',
    },
    {
      label: '包含',
      value: 'like',
    },
  ];

  const tjObj = ref({
    sourceCondField: '',
    token: '=',
    fieldOpener: '',
  });
  const handleCreate = () => {
    if (!tjObj.value.sourceCondField) {
      message.warning('请选择源表单');
      return;
    }
    conds.value +=
      `${tjObj.value.sourceCondField} ${tjObj.value.token}` +
      ' {$' +
      `${tjObj.value.fieldOpener}` +
      '}';
    setEmit();
  };

  const formGetFieldsDataMian = ref<Recordable[]>([]);
  //获取目标字段
  const getFormGetFieldsDataMian = () => {
    try {
      if (currentRoute.value?.query.formCode) {
        getFormGetFields({ formCode: currentRoute.value.query.formCode }).then((res) => {
          formGetFieldsDataMian.value = res || [];
          if (isArray(formGetFieldsDataMian.value)) {
            formGetFieldsDataMian.value.forEach((item) => {
              delete item.options;
            });
            tjObj.value.fieldOpener = formGetFieldsDataMian.value[0].name;
          }
        });
      }
    } catch (err) {
      console.log('getFormGetFields', err);
    }
  };

  const fetch = async () => {
    await getFormGetFieldsDataMian();
    let serverInfo = userStore.getServerInfo;
    isScriptEditable.value = serverInfo.isScriptEditable;
    console.log('isScriptEditable', isScriptEditable.value);
  };

  onMounted(fetch);

  const userStore = useUserStore();
  const ifrmRef = ref<any>(null);
  let ideUrl = 'script_frame.jsp';
  const onMessage = (e) => {
    var d = e.data;
    var data = d.data;
    var type = d.type;
    if (type == 'setScript') {
      console.log('onMessage data', data);
      conds.value = data;
      setEmit();
      if (d.cwsToken != null) {
        let cwsToken = d.cwsToken;
        ideUrl = 'script_frame.jsp?cwsToken=' + cwsToken;
      }
      closeModal();
    } else if (type == 'getScript') {
      let serverInfo = userStore.getServerInfo;
      console.log('getScript scriptStr.value=', conds.value);
      let data = {
        type: 'openerScript',
        version: serverInfo.version,
        spVersion: serverInfo.spVersion,
        scene: 'module.filter',
        data: conds.value ? conds.value : '',
      };
      // window.postMessage(data, '*');
      unref(ifrmRef)?.doPostMessage(data);
    } else if (type == 'setCwsToken') {
      let cwsToken = d.cwsToken;
      ideUrl = 'script_frame.jsp?cwsToken=' + cwsToken;
    }
  };

  if (window.addEventListener) {
    // all browsers except IE before version 9
    window.addEventListener('message', onMessage, false);
  }
  onUnmounted(() => {
    console.log('NodeEdit-onUnmounted');
    window.removeEventListener('message', onMessage, false);
  });

  const getPopupContainer = (triggerNode) => triggerNode?.parentNode;
</script>
